package com.glodon.paas.document.dao.mongo;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.glodon.paas.document.constant.DocumentConstant;
import com.glodon.paas.document.dao.ShareDao;
import com.glodon.paas.document.dao.domain.ShareEntity;
import com.google.code.morphia.query.Query;

public class ShareDaoMongoImpl extends MongoDBDao<ShareEntity, String> implements ShareDao {

    @Override
    public void ensureIndexes() {
        super.ensureIndexes();
        mongoDataStore.ensureIndex(this.entityClazz, "sharedUserId, toUserId, fileId");
    }

    @Override
    public List<ShareEntity> getShareForMe(String userId, String fileId) {
        Query<ShareEntity> q = this.createQuery().filter("toUserId", userId);
        if (StringUtils.isNotBlank(fileId)) {
            q.filter("fileId", fileId);
        }
        return q.asList();
    }

    @Override
    public List<ShareEntity> getShareByMe(String userId, String fileId, Integer shareType) {
        Query<ShareEntity> q = this.createQuery().filter("sharedUserId", userId);
        if (StringUtils.isNotBlank(fileId)) {
            q.filter("fileId", fileId);
        }
        if (shareType != null) {
            q.filter("shareType =", shareType);
        }
        return q.asList();
    }

    @Override
    public boolean isSharedFile(String fileId) {
        Query<ShareEntity> q = this.createQuery().filter("fileId =", fileId).filter("shareType =",
                                                                                    DocumentConstant.SHARE_TYPE_SHARED);
        return q.get() != null;
    }

    @Override
    public long getShareCount(String fileId, Integer shareType) {
        Query<ShareEntity> q = this.createQuery().filter("fileId =", fileId);
        if (shareType != null) {
            q.filter("shareType =", shareType);
        }
        return q.countAll();
    }

    @Override
    public void deleteByFile(String fileId, Integer shareType) {
        Query<ShareEntity> q = this.createQuery().filter("fileId =", fileId);
        if (shareType != null) {
            q.filter("shareType =", shareType);
        }
        super.deleteByQuery(q);
    }

    @Override
    public void deleteByOwner(String ownerId) {
        Query<ShareEntity> q = this.createQuery().filter("sharedUserId =", ownerId);
        super.deleteByQuery(q);
    }

    @Override
    public boolean isPublishedFile(String fileId) {
        return this.getShareCount(fileId, DocumentConstant.SHARE_TYPE_PUBLISHED) > 0;
    }

}
